package tk.heimashuma.store.annotation;

import com.fasterxml.jackson.annotation.JsonFilter;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ser.impl.SimpleBeanPropertyFilter;
import com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider;

public class CustomerJsonSerializer {
    static final String DYNC_INCLUDE = "DYNC_INCLUDE";
    static final String DYNC_FILTER = "DYNC_FILTER";
    ObjectMapper mapper = new ObjectMapper();
    @JsonFilter(DYNC_FILTER)
    interface DynamicFilter{}
    @JsonFilter(DYNC_INCLUDE)
    interface DynamicInclude{}
    public void filter (Class<?>clazz,String include,String filter){
        if(clazz == null) return ;
        if(include != null && include.trim().length()> 0){
            // 添加要包含转换的字段
            mapper.setFilterProvider(new SimpleFilterProvider().addFilter(DYNC_INCLUDE,
                    SimpleBeanPropertyFilter.filterOutAllExcept(include.split(","))));
            mapper.addMixIn(clazz,DynamicInclude.class);
        }else if(filter != null && filter.trim().length() > 0){
            // 移除不要转换的字段
            mapper.setFilterProvider(new SimpleFilterProvider().addFilter(DYNC_FILTER,
                    SimpleBeanPropertyFilter.serializeAllExcept(filter.split(","))));
            mapper.addMixIn(clazz,DynamicFilter.class);
        }
    }
    public String toJson(Object object) throws JsonProcessingException {
        return mapper.writeValueAsString(object);
    }
}
